<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/6/4
 * Time: 11:04
 */
namespace app\common\service;
use app\common\model\User;
use think\Cookie;
use think\Hook;
use think\Model;
use think\Request;
use think\Response;
use think\Session;

class UserService
{
    //错误信息
    public $error = '';
    //手机号码正则
    private $_tel_reg = '/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/';
    //用户名正则
    private $_uname = '/^[A-Za-z\x{4e00}-\x{9fa5}_]{1}[A-Za-z0-9\x{4e00}-\x{9fa5}_]{1,19}$/u';
    public function __construct()
    {
        Cookie::init([
            'prefix'=>config('cookie_prefix'),
            'httponly'=>true,
        ]);
    }

    /**
     * 用户登录
     * @param string $loginId 用户唯一标识 [用户名|手机号码]
     * @param string $pwd
     * @param bool $isRememberMe 是否记录登录状态，默认为true
     * @return bool|static
     */
    public function login($loginId , $pwd , $isRememberMe = true){

        //是否为手机号码
        if(preg_match($this->_tel_reg,$loginId)){
            //是否为用户名
            $condition['phone'] = $loginId;
        }elseif(preg_match($this->_uname,$loginId)){
            $condition['uname'] = $loginId;
        }else{
            //用户名错误
            $this->error = lang('user name error');
            return false;
        }
        $condition['is_del'] = User::NOT_DELETED;
        $user = User::get($condition);

        if(md5(md5($pwd).$user->login_salt) != $user->pwd){
            //密码错误
            $this->error = lang('password error');
            return false;
        }else{
            //登录成功
            $this->_recordLogin($user , $isRememberMe);
            return $user;
        }
    }
    /**
     * 设置登录状态、记录登录知识
     * @param User $user 用户对象
     * @param boolean $isRememberMe 是否记录登录状态，默认为true
     */
    private function _recordLogin($user, $isRememberMe = true) {

        //注册session
        Session::set('site_key',getSiteKey());
        Session::set('uid',$user->id);
        //注册cookie
        if(!$this->getCookieUid() && $isRememberMe) {
            $expire = 3600 * 24 * 30;//自动登录的有效期
            Cookie::init(['expire'=>$expire]);
            Cookie::set('logged_user', $this->jiami(config('site_key').'.'.$user->id));
        }
        //更新登录时间很登录的ip
        $user->login_time = time();
        $user->login_ip = Request::instance()->ip(1);
        $user->save();
        //触发登录成功事件
        Hook::listen('user_login',$user);
    }

    /**
     * 用户是否已经登录
     */
    public function isLogged(){
        // 验证本地系统登录
        if(Session::has('uid') && Session::get('site_key')==getSiteKey()) {
            return true;
        } else if($uid = $this->getCookieUid()) {
            $user = $this->findUserById($uid);
            $this->_recordLogin($user , false);
            return true;
        } else {
            //没有登录
            $this->logout();
            return false;
        }
    }
    /**
     * 注销登录
     */
    public function logout(){
        //监听注销事件
        Hook::listen('logout');
        //注销session
        Session::delete('mid');
        Session::delete('site_key');
        //注销cookie
        Cookie::delete('logged_user');


    }
    /**
     * 是否需要登录
     * @return bool 是否允许访问
     */
    public function needLogin(){
        static $allow_access = null;

        if(is_null($allow_access)){
            //获取允许访问的模块/控制器/方法
            $allow_access = config('allow_access');
        }

        $temp1 = MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME;
        $temp2 = MODULE_NAME.'/'.CONTROLLER_NAME.'/*';
        $temp3 = MODULE_NAME.'/*/*';
        return !( (isset($allow_access[$temp1]) && $allow_access[$temp1] === true)
            || (isset($allow_access[$temp2]) &&  $allow_access[$temp2] === true)
            || (isset($allow_access[$temp3]) && $allow_access[$temp3]) === true);
    }
    /**
     * 获取cookie中记录的用户ID
     * @return integer cookie中记录的用户ID
     */
    public function getCookieUid() {
        static $cookie_uid = null;
        if(isset($cookie_uid) && $cookie_uid !== null) {
            return $cookie_uid;
        }

        $cookie = Cookie::get('logged_user');
        $cookie = explode('.', $this->jiemi($cookie),2);
        $cookie_uid = ($cookie[0] != config('site_key')) ? false : $cookie[1];
        return $cookie_uid;
    }
    /**
     * 加密函数
     * @param string $txt 需加密的字符串
     * @param string $key 加密密钥，默认读取SECURE_CODE配置
     * @return string 加密后的字符串
     */
    private function jiami($txt, $key = null)
    {
        empty($key) && $key = config('site_key');
        return tsauthcode($txt, 'ENCODE', $key);
    }
    /**
     * 解密函数
     * @param string $txt 待解密的字符串
     * @param string $key 解密密钥，默认读取SECURE_CODE配置
     * @return string 解密后的字符串
     */
    private function jiemi($txt, $key = null)
    {
        empty($key) && $key = config('site_key');
        return tsauthcode($txt, 'DECODE', $key);
    }

    /**
     * 根据id返回用户
     * @param $id
     * @return static
     */
    public function findUserById($id){
        return User::get(['id'=>$id,'is_del'=>User::NOT_DELETED]);
    }
}